<template>
  <div class="chat-room-container">
    <div class="chat-header">
      <h2>多人聊天室</h2>
      <div class="connection-status" :class="connectionStatus">
        <span class="status-indicator"></span>
        {{ statusText }}
        <button @click="checkConnection" class="check-btn">检查连接</button>
        <!-- 添加搜索按钮 -->
        <button 
          @click="openSearchDialog"
          class="tool-button search-button"
        >
          <el-icon><Search/></el-icon> 搜索
        </button>
      </div>
    </div>
    <!-- 搜索面板 -->
    <el-dialog
      v-model="searchDialogVisible"
      title="搜索聊天记录"
      width="70%"
      center
    >
      <div class="search-options">
        <el-date-picker
          v-model="searchDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px; margin-right: 12px;"
          @change="searchByDate"
        />
        <el-button icon="Picture" @click="viewAllImages" class="search-option-btn">
          查看所有图片
        </el-button>
        <el-button icon="Document" @click="viewAllFiles" class="search-option-btn">
          查看所有文件
        </el-button>
      </div>
      
      <!-- 搜索结果展示 -->
      <div v-if="searchResultsVisible" class="search-results">
        <h3 class="search-results-title">{{ searchResultsTitle }}</h3>
        
        <!-- 日期搜索结果 -->
        <div v-if="searchType === 'date' && filteredMessages.length > 0" class="date-search-results">
          <div 
            v-for="msg in filteredMessages" 
            :key="msg.timestamp + msg.sender"
            class="search-result-item"
          >
            <span class="result-sender">{{ msg.sender }}:</span>
            <span class="result-content">{{ getMessageSummary(msg) }}</span>
            <span class="result-time">{{ formatTime(msg.timestamp) }}</span>
          </div>
        </div>
        
        <!-- 图片列表 -->
        <div v-else-if="searchType === 'images'" class="media-grid">
          <div 
            v-for="(image, index) in allImages" 
            :key="`image-${index}`"
            class="media-item"
            @click="previewImage(image.fileInfo.URL)"
          >
            <img :src="image.fileInfo.URL" :alt="image.fileInfo.Name" class="media-thumbnail">
            <div class="media-info">
              <span>{{ image.sender }}</span>
              <span>{{ formatTime(image.timestamp) }}</span>
            </div>
          </div>
          <!-- 分页 -->
          <div v-if="allImages.length > 0" class="pagination">
            <el-pagination
              v-model:current-page="imageCurrentPage"
              :page-sizes="[9, 18, 27]"
              :page-size="imagePageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalImages"
              @size-change="handleImageSizeChange"
              @current-change="handleImageCurrentChange"
            />
          </div>
        </div>
        
        <!-- 文件列表 -->
        <div v-else-if="searchType === 'files'" class="file-list">
          <div 
            v-for="(file, index) in allFiles" 
            :key="`file-${index}`"
            class="file-list-item"
          >
            <el-icon><Document/></el-icon>
            <div class="file-list-info">
              <a :href="file.fileInfo.URL" :download="file.fileInfo.Name" class="file-list-name">{{ file.fileInfo.Name }}</a>
              <div class="file-list-meta">
                <span>{{ file.sender }}</span>
                <span>{{ formatFileSize(file.fileInfo.Size) }}</span>
                <span>{{ formatTime(file.timestamp) }}</span>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div v-if="allFiles.length > 0" class="pagination">
            <el-pagination
              v-model:current-page="fileCurrentPage"
              :page-sizes="[10, 20, 30]"
              :page-size="filePageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalFiles"
              @size-change="handleFileSizeChange"
              @current-change="handleFileCurrentChange"
            />
          </div>
        </div>
        
        <!-- 无结果提示 -->
        <div v-else-if="searchResultsVisible" class="no-search-results">
          未找到相关内容
        </div>
      </div>
    </el-dialog>
    
    <div class="chat-messages" ref="messageContainer" @scroll="handleScroll">
      <div v-if="loadingMore" class="loading-more">加载历史消息中...</div>
      
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        class="message-wrapper"
        :class="{
          'message-self': message.sender === currentUser,
          'message-other': message.sender !== currentUser,
          'message-system': message.type === 'system'
        }"
      >
        <div v-if="message.type !== 'system'" class="message-avatar">{{ getAvatarText(message.sender) }}</div>
        <div class="message-content-wrapper">
          <div v-if="message.type !== 'system'" class="message-sender">{{ message.sender }}</div>
          
          <div class="message-content" v-if="message.type === 'text'">
            {{ message.content }}
          </div>
          
          <div class="message-content" v-else-if="message.type === 'image' && message.fileInfo">
            <img 
              :src="message.fileInfo.URL" 
              :alt="message.fileInfo.Name || '图片'"
              class="message-image"
              @click="previewImage(message.fileInfo.URL)"
            >
            <div class="image-info">
              <span>{{ message.fileInfo.Name }}</span>
              <span>{{ formatFileSize(message.fileInfo.Size) }}</span>
            </div>
          </div>
          <div class="message-content" v-else-if="message.type === 'file' && message.fileInfo">
            <div class="file-item">
              <i class="el-icon-document"></i>
              <div class="file-info">
                <a :href="message.fileInfo.URL" :download="message.fileInfo.Name" class="file-name">{{ message.fileInfo.Name }}</a>
                <span>{{ formatFileSize(message.fileInfo.Size) }}</span>
              </div>
            </div>
          </div>
          <div v-else class="message-content">
            {{ message.content }}
          </div>
          
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
      
      <div v-if="messages.length === 0 && !loadingMore" class="no-messages">暂无消息</div>
    </div>
    
    <div class="chat-input-area">
      <div class="input-toolbar">
        <input 
          type="file" 
          ref="fileInput"
          style="display: none"
          @change="handleFileSelect"
        >
        <el-button 
          @click="$refs.fileInput.click()"
          class="tool-button"
          :disabled="connectionStatus !== 'connected'"
          icon="Files" 
        >
          上传文件
        </el-button>
        
        <div v-if="uploadingFile" class="upload-progress">
          <el-progress :percentage="uploadProgress" :stroke-width="2" style="width: 120px;"></el-progress>
        </div>
      </div>
      
      <div class="input-wrapper">
        <textarea 
          v-model="messageText"
          placeholder="输入消息..."
          rows="3"
          class="message-input"
          :disabled="connectionStatus !== 'connected'"
          @keyup.enter.exact.prevent="sendMessage"
        ></textarea>
        <button 
          @click="sendMessage"
          class="send-button"
          :disabled="!messageText.trim() || connectionStatus !== 'connected'"
        >
          发送
        </button>
      </div>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="90%"
      center
    >
      <img :src="previewImageUrl" style="max-width: 100%; max-height: 80vh;">
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick,computed } from 'vue';
import { useWebSocketStore } from '../stores/websocket';
import { useUserStore } from '../stores/user';
import { ElMessage, ElProgress, ElDialog,ElDatePicker, ElPagination } from 'element-plus';
// 添加 fileServerApi 导入
import fileServerApi from '../api/fileServer';

// Store
const wsStore = useWebSocketStore();
const userStore = useUserStore();

// 状态管理
const messageContainer = ref(null);
const messages = ref([]);
const messageText = ref('');
const connectionStatus = ref('disconnected'); // connected, connecting, disconnected
const statusText = ref('未连接');
const currentUser = ref('');
const loadingMore = ref(false);
const hasMoreHistory = ref(true);
const pageSize = 10;
const currentPage = ref(0);
const uploadingFile = ref(false);
const uploadProgress = ref(0);
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

// 搜索功能
const searchDialogVisible = ref(false);
const searchResultsVisible = ref(false);
const searchDate = ref('');
const searchType = ref('');
const searchResultsTitle = ref('');
const filteredMessages = ref([]);
const filteredPageSize = ref(100);
const filteredCurrentPage = ref(0);
const filteredHasMoreHistory = ref(true);

// // 图片分页相关状态
const totalImages = ref(0);
const imageCurrentPage = ref(1);
const imagePageSize = ref(9);
const allImages = ref([]);
const paginatedImages = computed(() => {
  const startIndex = (imageCurrentPage.value - 1) * imagePageSize.value;
  const endIndex = startIndex + imagePageSize.value;
  return allImages.value.slice(startIndex, endIndex);
});

// 文件分页相关状态
const totalFiles = ref(0);
const fileCurrentPage = ref(1);
const filePageSize = ref(10);
const allFiles = ref([]);
const paginatedFiles = computed(() => {
  const startIndex = (fileCurrentPage.value - 1) * filePageSize.value;
  const endIndex = startIndex + filePageSize.value;
  return allFiles.value.slice(startIndex, endIndex);
});

const openSearchDialog = () => {
  searchDialogVisible.value = true;
  searchResultsVisible.value = false;
};


// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取头像文本（用户名的第一个字符）
const getAvatarText = (username) => {
  return username ? username.charAt(0).toUpperCase() : '?';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B';
  else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
  else return (bytes / 1048576).toFixed(2) + ' MB';
};

// 连接WebSocket
const connect = async () => {
  try {
    connectionStatus.value = 'connecting';
    statusText.value = '连接中...';
    
    // 获取用户token
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未登录，请先登录');
    }
    
    await userStore.restoreUser();
    currentUser.value = userStore.state.username || '匿名用户';
    
    
    // 连接WebSocket
    wsStore.connect(token);
    
    // 设置消息监听器
    setupMessageListeners();
    

  } catch (error) {
    connectionStatus.value = 'disconnected';
    statusText.value = '连接失败';
    addSystemMessage(`连接失败: ${error.message}`);
  }
};

// 设置消息监听器
const setupMessageListeners = () => {
  if (!wsStore.ws) return;

  // 保存原始的onmessage处理函数
  const originalOnMessage = wsStore.ws.onmessage;
  
  // 重写onmessage处理函数
  wsStore.ws.onmessage = (event) => {
    console.log('收到消息');
    // 调用原始的处理函数
    if (originalOnMessage) {
      originalOnMessage(event);
    }
    
    // 处理消息并显示在界面上
    try {
      const data = JSON.parse(event.data);
      
      // 处理正常消息
      if (data.code === 0 && data.data) {
        if (data.data.msgList && data.data.type == 'get_history') {
          console.log("收到history消息多个消息");
          // 把list倒过来
          data.data.msgList.reverse();
          handleBatchMessages(data.data.msgList);
        } else if (data.data.msgList && data.data.type == 'search_date') {
          console.log("收到查询消息")
          data.data.msgList.reverse();
          handleSearchMessages(data.data.msgList);
        }else{
          console.log("收到单个消息")
          const message = data.data;
          console.log('添加消息', message);
          // 确保消息结构符合要求
          if (message.sender && (message.content || (message.fileInfo && message.fileInfo.URL))) {
              console.log('添加消息成功:');
            // 添加到消息列表
            messages.value.push({
              ...message,
              timestamp: message.timestamp || Date.now()
            });
            // 滚动到底部
            scrollToBottom();
          }
        }
      } 
      // 处理批量历史消息
      else if (data.code === -1 && data.data && Array.isArray(data.data)) {
        handleBatchMessages(data.data);
      }
    } catch (error) {
      console.error('解析消息失败:', error);
      addSystemMessage(`接收消息格式错误: ${error.message}`);
    }
  };

  // 监听连接打开事件
  wsStore.ws.onopen = (event) => {
    connectionStatus.value = 'connected';
    statusText.value = '已连接';
    addSystemMessage('WebSocket连接成功！');
    // 加载初始历史消息
    loadMoreHistory();
  };

  // 监听连接关闭事件
  wsStore.ws.onclose = (event) => {
    connectionStatus.value = 'disconnected';
    statusText.value = '已断开连接';
    addSystemMessage(`连接已关闭: 代码 ${event.code}, 原因: ${event.reason}`);
  };

  // 监听错误事件
  wsStore.ws.onerror = (error) => {
    addSystemMessage(`WebSocket错误: ${error.message || '未知错误'}`);
  };
};

// 处理批量消息
const handleBatchMessages = (batchMessages) => {
  if (batchMessages.length === 0) {
    hasMoreHistory.value = false;
    addSystemMessage('没有更多历史消息了');
    return;
  }
  
  // 将历史消息添加到列表开头
  const formattedMessages = batchMessages.map(msg => ({
    ...msg,
    timestamp: msg.timestamp || Date.now()
  }));
  
  // 保存当前滚动位置
  const scrollTop = messageContainer.value.scrollTop;
  const scrollHeight = messageContainer.value.scrollHeight;
  
  // 添加消息到列表开头
  messages.value.unshift(...formattedMessages);
  
  // 调整滚动位置，保持用户查看的位置不变
  nextTick(() => {
    const newScrollHeight = messageContainer.value.scrollHeight;
    messageContainer.value.scrollTop = newScrollHeight - (scrollHeight - scrollTop);
  });
  
  // 如果返回的消息数量少于页面大小，说明没有更多历史消息
  if (batchMessages.length < pageSize) {
    hasMoreHistory.value = false;
  }
  
  currentPage.value++;
};

// 处理查询消息
const handleSearchMessages = (batchMessages) => {
  if (batchMessages.length === 0) {
    filteredHasMoreHistory.value = false;
    addSystemMessage('没有更多历史消息了');
    return;
  }
  
  // 将历史消息添加到列表开头
  const formattedMessages = batchMessages.map(msg => ({
    ...msg,
    timestamp: msg.timestamp || Date.now()
  }));
  
  // 保存当前滚动位置
  // const scrollTop = messageContainer.value.scrollTop;
  // const scrollHeight = messageContainer.value.scrollHeight;
  
  // 添加消息到列表开头
  filteredMessages.value.unshift(...formattedMessages);
  console.log("查询date的消息数据",filteredMessages.value);
  
  
  // 调整滚动位置，保持用户查看的位置不变
  // nextTick(() => {
  //   const newScrollHeight = messageContainer.value.scrollHeight;
  //   messageContainer.value.scrollTop = newScrollHeight - (scrollHeight - scrollTop);
  // });
  
  // 如果返回的消息数量少于页面大小，说明没有更多历史消息
  if (batchMessages.length < filteredPageSize.value) {
    filteredHasMoreHistory.value = false;
  }

  if (filteredMessages.value.length === 0) {
    filteredHasMoreHistory.value = false;
    // addSystemMessage('没有搜索到消息');
    return;
  }

  filteredHasMoreHistory.value = true;
  searchResultsVisible.value = true;
  searchType.value = 'date';
  filteredCurrentPage.value++;
};

// 加载更多历史消息
const loadMoreHistory = async () => {
  if (loadingMore.value || !hasMoreHistory.value || connectionStatus.value !== 'connected') {
    console.log('获取历史中止：', loadingMore.value, connectionStatus.value);
    return;
  }
  
  // loadingMore.value = true;
  
  try {
    // 请求历史消息
    const request = {
      type: 'get_history',
      recipient: String(userStore.state.user_id),
      offset: currentPage.value * pageSize,
      limit: pageSize
    };
    
    wsStore.send(request);
    
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
  } catch (error) {
    addSystemMessage(`加载历史消息失败: ${error.message}`);
  } finally {
    loadingMore.value = false;
  }
};

// 滚动处理
const handleScroll = () => {
  const container = messageContainer.value;
  if (!container || loadingMore.value) return;
  
  // 当滚动到顶部时，加载更多历史消息
  if (container.scrollTop === 0 && hasMoreHistory.value) {
    loadMoreHistory();
  }
};

// 发送消息
const sendMessage = () => {
  if (!messageText.value.trim() || connectionStatus.value !== 'connected') {
    return;
  }

  try {
    const messageObj = {
      sender: currentUser.value,
      sender_id: String(userStore.state.user_id),
      content: messageText.value,
      type: 'text',
      timestamp: Date.now()
    };

    console.log('发送消息:', messageObj);
    
    
    wsStore.send(messageObj);
    
    // 直接添加到消息列表（乐观更新）
    messages.value.push(messageObj);
    
    // 清空输入框
    messageText.value = '';
    
    // 滚动到底部
    scrollToBottom();
  } catch (error) {
    addSystemMessage(`发送失败: ${error.message}`);
  }
};

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 重置文件输入
  event.target.value = '';
  
  // 检查文件类型
  // if (!file.type.startsWith('image/')) {
  //   ElMessage.warning('请选择图片文件');
  //   return;
  // }
  
  // 检查文件大小（限制2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning('文件大小不能超过2MB');
    return;
  }
  
  // 上传图片
    // 根据文件类型调用不同的上传函数
  if (file.type.startsWith('image/')) {
    uploadImage(file);
  } else {
    uploadFile(file);
  }
};


// 添加新的文件上传函数，用于处理非图片文件
const uploadFile = async (file) => {
  if (connectionStatus.value !== 'connected') {
    ElMessage.warning('WebSocket未连接，无法上传文件');
    return;
  }
  
  uploadingFile.value = true;
  uploadProgress.value = 0;
  
  try {
    // 使用与图片上传相同的API
    const formData = new FormData();
    formData.append('file', file);
    
    // 创建模拟进度的函数
    const simulateProgress = () => {
      return new Promise((resolve) => {
        const interval = setInterval(() => {
          uploadProgress.value += 5;
          if (uploadProgress.value >= 90) {
            clearInterval(interval);
            resolve();
          }
        }, 100);
      });
    };
    
    // 启动进度模拟
    const progressPromise = simulateProgress();
    
    // 执行实际的文件上传
    const res = await fileServerApi.imageUpload(formData);
    
    // 等待进度模拟完成
    await progressPromise;
    
    if (res.url) {
      // 构造文件消息
      const fileMessage = {
        sender: currentUser.value,
        sender_id: String(userStore.state.user_id),
        type: 'file', // 使用新的消息类型
        timestamp: Date.now(),
        fileInfo: {
          Name: file.name,
          Size: file.size,
          Type: file.type,
          URL: res.domain + res.path + "?download=1" // 设置为下载模式
        }
      };
      
      // 发送文件消息
      wsStore.send(fileMessage);
      
      // 添加到消息列表
      messages.value.push(fileMessage);
      
      uploadProgress.value = 100;
      
      // 滚动到底部
      scrollToBottom();
      
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    ElMessage.error(`文件上传失败: ${error.message || '未知错误'}`);
  } finally {
    // 延迟重置上传状态，让用户看到完成状态
    setTimeout(() => {
      uploadingFile.value = false;
      uploadProgress.value = 0;
    }, 500);
  }
};

// 修改上传图片函数，使用与 WriteArticle.vue 相同的接口
const uploadImage = async (file) => {
  if (connectionStatus.value !== 'connected') {
    ElMessage.warning('WebSocket未连接，无法上传图片');
    return;
  }
  
  uploadingFile.value = true;
  uploadProgress.value = 0;
  
  try {
    // 使用 fileServerApi.imageUpload 上传图片
    const formData = new FormData();
    formData.append('file', file);
    
    // 创建模拟进度的函数
    const simulateProgress = () => {
      return new Promise((resolve) => {
        const interval = setInterval(() => {
          uploadProgress.value += 5;
          if (uploadProgress.value >= 90) {
            clearInterval(interval);
            resolve();
          }
        }, 100);
      });
    };
    
    // 启动进度模拟
    const progressPromise = simulateProgress();
    
    // 执行实际的图片上传
    const res = await fileServerApi.imageUpload(formData);
    
    // 等待进度模拟完成
    await progressPromise;
    
    if (res.url) {
      // 构造图片消息
      const imageMessage = {
        sender: currentUser.value,
        sender_id: String(userStore.state.user_id),
        type: 'image',
        timestamp: Date.now(),
        fileInfo: {
          Name: file.name,
          Size: file.size,
          Type: file.type,
          URL: res.domain + res.path + "?download=0"
        }
      };
      
      // 发送图片消息
      wsStore.send(imageMessage);
      
      // 添加到消息列表
      messages.value.push(imageMessage);
      
      uploadProgress.value = 100;
      
      // 滚动到底部
      scrollToBottom();
      
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    ElMessage.error(`图片上传失败: ${error.message || '未知错误'}`);
  } finally {
    // 延迟重置上传状态，让用户看到完成状态
    setTimeout(() => {
      uploadingFile.value = false;
      uploadProgress.value = 0;
    }, 500);
  }
};

// 预览图片
const previewImage = (url) => {
  previewImageUrl.value = url;
  imagePreviewVisible.value = true;
};

// 检查连接状态
const checkConnection = () => {
  const state = wsStore.ws ? wsStore.ws.readyState : -1;
  let stateText = '';
  
  switch(state) {
    case WebSocket.CONNECTING: stateText = '连接中 (CONNECTING)'; break;
    case WebSocket.OPEN: stateText = '已连接 (OPEN)'; break;
    case WebSocket.CLOSING: stateText = '关闭中 (CLOSING)'; break;
    case WebSocket.CLOSED: stateText = '已关闭 (CLOSED)'; break;
    default: stateText = '未初始化'; break;
  }
  
  ElMessage.info(`当前连接状态: ${stateText}`);
};

// 添加系统消息
const addSystemMessage = (content) => {
  messages.value.push({
    type: 'system',
    content,
    timestamp: Date.now()
  });
  scrollToBottom();
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  }, 100);
};


// 搜索功能相关函数
const toggleSearchPanel = () => {
  searchDialogVisible.value = !searchDialogVisible.value;
  if (!searchDialogVisible.value) {
    searchResultsVisible.value = false;
  }
};

const searchByDate = () => {
  if (!searchDate.value) return;
  
  // const selectedDate = new Date(searchDate.value);
  // 重置时间为00:00:00
  // selectedDate.setHours(0, 0, 0, 0);
  
  // console.log(selectedDate.toISOString().split('T')[0]);
  // const nextDay = new Date(selectedDate);
  // nextDay.setDate(nextDay.getDate() + 1);
  filteredMessages.value = [];
  filteredCurrentPage.value = 0;
  filteredPageSize.value = 100;
  searchResultsVisible.value = false;
  searchType.value = 'date';
  searchResultsTitle.value = `搜索 ${searchDate.value} 的消息`;
  
  // 过滤出选定日期的消息
  const searchMessage = {
    type: 'search_date',
    sender: currentUser.value,
    Recipient: String(userStore.state.user_id),
    date: searchDate.value,
    limit: filteredPageSize.value,
    offset: filteredCurrentPage.value * filteredPageSize.value,
  }
  // 发送搜索消息
  wsStore.send(searchMessage);

  // if (filteredMessages.value.length === 0) {
  //   filteredHasMoreHistory.value = false;
  //   addSystemMessage('没有搜索到消息');
  //   return;
  // }
  // filteredMessages.value = messages.value.filter(msg => {
  //   const msgDate = new Date(msg.timestamp);
  //   return msgDate >= selectedDate && msgDate < nextDay;
  // }).sort((a, b) => a.timestamp - b.timestamp);
  
};

const viewAllImages = () => {
  // 收集所有图片消息
  allImages.value = messages.value
    .filter(msg => msg.type === 'image' && msg.fileInfo)
    .sort((a, b) => b.timestamp - a.timestamp); // 按时间倒序
  
  totalImages.value = allImages.value.length;
  imageCurrentPage.value = 1;
  
  searchType.value = 'images';
  searchResultsTitle.value = `所有图片 (${totalImages.value})`;
  searchResultsVisible.value = true;
};

const viewAllFiles = () => {
  // 收集所有文件消息
  allFiles.value = messages.value
    .filter(msg => msg.type === 'file' && msg.fileInfo)
    .sort((a, b) => b.timestamp - a.timestamp); // 按时间倒序
  
  totalFiles.value = allFiles.value.length;
  fileCurrentPage.value = 1;
  
  searchType.value = 'files';
  searchResultsTitle.value = `所有文件 (${totalFiles.value})`;
  searchResultsVisible.value = true;
};

const scrollToMessage = (timestamp) => {
  // 找到对应时间戳的消息元素并滚动到视图
  nextTick(() => {
    const messageElements = messageContainer.value.querySelectorAll('.message-wrapper');
    for (let i = 0; i < messageElements.length; i++) {
      const message = messages.value[i];
      if (message && message.timestamp === timestamp) {
        messageElements[i].scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        });
        // 高亮显示找到的消息
        messageElements[i].classList.add('highlighted-message');
        setTimeout(() => {
          messageElements[i].classList.remove('highlighted-message');
        }, 2000);
        break;
      }
    }
    // 关闭搜索面板
    searchDialogVisible.value = false;
    searchResultsVisible.value = false;
  });
};

const getMessageSummary = (message) => {
  if (message.type === 'text') {
    return message.content.length > 50 ? message.content.substring(0, 50) + '...' : message.content;
  } else if (message.type === 'image') {
    return '[图片] ' + (message.fileInfo?.Name || '图片文件');
  } else if (message.type === 'file') {
    return '[文件] ' + (message.fileInfo?.Name || '文件');
  } else {
    return message.content || '';
  }
};

// 分页处理函数
const handleImageSizeChange = (size) => {
  imagePageSize.value = size;
  imageCurrentPage.value = 1;
};

const handleImageCurrentChange = (current) => {
  imageCurrentPage.value = current;
};

const handleFileSizeChange = (size) => {
  filePageSize.value = size;
  fileCurrentPage.value = 1;
};

const handleFileCurrentChange = (current) => {
  fileCurrentPage.value = current;
};

// 断开连接
const disconnect = () => {
  wsStore.disconnect();
};

// 组件挂载时
onMounted(() => {
  connect();
});

// 组件卸载时
onUnmounted(() => {
  disconnect();
});
</script>

<style scoped>
.chat-room-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1800px;
  margin: 50px 100px 100px 100px;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chat-header h2 {
  margin: 0;
  color: #303133;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
}

.connection-status.connected .status-indicator {
  background-color: #67c23a;
}

.connection-status.connecting .status-indicator {
  background-color: #e6a23c;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.check-btn {
  padding: 4px 12px;
  font-size: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s;
}

.check-btn:hover {
  color: #409eff;
  border-color: #409eff;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.loading-more {
  text-align: center;
  padding: 10px;
  color: #909399;
  font-size: 14px;
}

.message-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.message-self {
  flex-direction: row-reverse;
}

.message-system {
  justify-content: center;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.message-content-wrapper {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-self .message-content-wrapper {
  align-items: flex-end;
}

.message-sender {
  font-size: 12px;
  color: #909399;
}

.message-content {
  background-color: #fff;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-break: break-word;
  white-space: pre-wrap;
}

.message-self .message-content {
  background-color: #409eff;
  color: white;
}

.message-system .message-content {
  background-color: #f0f9ff;
  color: #606266;
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 4px;
}

.message-image {
  max-width: 100%;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.message-image:hover {
  transform: scale(1.02);
}

.image-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #ffffff;
  margin-top: 4px;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3); /* 增加文字阴影增强可读性 */

}

.message-time {
  font-size: 11px;
  color: #c0c4cc;
}

.no-messages {
  text-align: center;
  color: #909399;
  padding: 40px;
  font-size: 14px;
}

.chat-input-area {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
}

.input-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.tool-button {
  padding: 6px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.tool-button:hover:not(:disabled) {
  color: #409eff;
  border-color: #409eff;
}

.tool-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.upload-progress {
  flex: 1;
}

.input-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}

.message-input:focus {
  outline: none;
  border-color: #409eff;
}

.message-input:disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.send-button {
  padding: 10px 24px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.send-button:hover:not(:disabled) {
  background-color: #66b1ff;
}

.send-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}
.file-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-width: 300px;
}

.file-item i {
  font-size: 24px;
  color: #409eff;
  margin-right: 10px;
}

.file-info {
  flex: 1;
}

.file-name {
  display: block;
  font-weight: 500;
  color: #409eff;
  text-decoration: none;
  margin-bottom: 4px;
}

.file-name:hover {
  text-decoration: underline;
}

.file-item span {
  font-size: 12px;
  color: #909399;
}

.dark-theme .chat-room-container {
  background-color: #1a1a1a;
}

.dark-theme .chat-header {
  background-color: #2c2c2c;
  border-bottom: 1px solid #404040;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.dark-theme .chat-header h2 {
  color: #ffffff;
}

.dark-theme .connection-status {
  color: #cccccc;
}

.dark-theme .chat-messages {
  background-color: #1a1a1a;
}

.dark-theme .message-content {
  background-color: #2c2c2c;
  color: #ffffff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.dark-theme .message-self .message-content {
  background-color: #409eff;
  color: white;
}

.dark-theme .message-system .message-content {
  background-color: #2a3a4a;
  color: #cccccc;
}

.dark-theme .message-sender {
  color: #cccccc;
}

.dark-theme .message-time {
  color: #666666;
}

.dark-theme .no-messages {
  color: #666666;
}

.dark-theme .chat-input-area {
  background-color: #2c2c2c;
  border-top: 1px solid #404040;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.3);
}

.dark-theme .tool-button {
  background-color: #3a3a3a;
  border-color: #505050;
  color: #cccccc;
}

.dark-theme .tool-button:hover:not(:disabled) {
  color: #409eff;
  border-color: #409eff;
}

.dark-theme .message-input {
  background-color: #3a3a3a;
  border-color: #505050;
  color: #ffffff;
}

.dark-theme .message-input:focus {
  border-color: #409eff;
}

.dark-theme .message-input:disabled {
  background-color: #2a2a2a;
}

.dark-theme .file-item {
  background-color: #3a3a3a;
}

.dark-theme .file-info span {
  color: #999999;
}

.dark-theme .image-info {
  color: #e9e1e1; /* 深色主题下使用更浅的颜色 */
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
}

.dark-theme .check-btn {
  background-color: #3a3a3a;
  border-color: #505050;
  color: #cccccc;
}

.dark-theme .check-btn:hover {
  color: #409eff;
  border-color: #409eff;
}

.search-date-picker {
  width: 150px;
}
.search-options{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  gap: 12px;
}
/* 日期搜索结果样式 */
.date-search-results {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 10px;
}

.search-result-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.search-result-item:hover {
  background-color: #f0f7ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.result-sender {
  font-weight: 600;
  color: #409eff;
  margin-right: 8px;
  min-width: 80px;
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  color: #303133;
  line-height: 1.5;
  word-break: break-word;
}

.result-time {
  font-size: 12px;
  color: #909399;
  margin-left: 12px;
  flex-shrink: 0;
}

/* 深色主题下的样式调整 */
.dark-theme .date-search-results {
  background-color: #2c2c2c;
}

.dark-theme .search-result-item {
  background-color: #3a3a3a;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.dark-theme .search-result-item:hover {
  background-color: #4a4a4a;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.dark-theme .result-sender {
  color: #66b1ff;
}

.dark-theme .result-content {
  color: #e4e7ed;
}

.dark-theme .result-time {
  color: #909399;
}

/* 确保深色主题下的图标颜色正确显示 */
.dark-theme .search-option-btn .el-icon {
  color: #cccccc;
}

.dark-theme .search-option-btn:hover .el-icon {
  color: #66b1ff;
}
</style>